<template>
	<div ref="mainBox">
		{{ sIndex }} {{ listFocus }}
		<el-popover
		    placement="bottom-start"
		    trigger="manual"
		    v-model="listVisible">
		    <el-input slot="reference" @change="inputChange" v-model="selectValue" :placeholder="placeholder" @focus="inputFocus = true; listVisible = true; search(selectValue)" @blur="inputFocus = false"></el-input>
		    <div class="infinite-list-wrapper" id="scrollTable">
		    	<!-- v-infinite-scroll="load" -->
		    	<el-table
		    		ref="singleTable"
		    		:data="list"
		    		:height="tableHeight"
		    		highlight-current-row
		    		@row-click="rowClick"
		    		:infinite-scroll-disabled="listDisabled"
		    		@current-change="handleCurrentChange"
		    		style="width: 100%">
		    		<el-table-column :key="item.key" v-for="item in config.keys" :label="item.name">
		    			<template slot-scope="scope">
		    				<template v-if="item.switch">
		    					<span :style="'color: ' + b.color" :key="b.name" v-if="eval(scope.row[b.key] + (b.symbol || '==') + b.value)" v-for="b in item.switch">{{ b.name }}</span>
		    				</template>
		    				<template v-else>
		    					{{ scope.row[item.key] }}
		    				</template>
		    			</template>
		    		</el-table-column>
		    	</el-table>
		    	<p v-if="loading">加载中...</p>
		    	<p v-if="noMore">没有更多了</p>
		    </div>
		</el-popover>
	</div>
</template>

<script>
	import request from "@/utils/request";
	export default {
		name: "searchInput",
		props: {
			value: {
				type: String,
				default: ''
			},
			config: {
				type: Object,
				default: () => {
					return {
						api: '/sinohis/pension/fee/itemmanager/searchAllItemInfos',
						method: 'post',
						postKey: 'mnemonicCodeOrName',
						label: 'name',
						value: 'mark',
						data: { nurseItemBol: true },
						keys: [
							{ name: '名称', key: 'name' },
							{ name: '价格', key: 'fee' },
						]
					}
				}
			},
			searchName: {
				type: String,
				default: ''
			},
			placeholder: {
				type: String,
				default: '请输入关键字'
			},
			disabled: {
				type: Boolean,
				default: false
			},
			tableHeight: {
				type: Number,
				default: 304
			},
		},
		data(){
			return {
				selectValue: '',
				list: [],
				changeValue: '',

				count: [],
				loading: false,
				listVisible: false,
				currentRow: {},
				sIndex: 0,
				listFocus: false,
				inputFocus: false,

			}
		},
		computed: {
			noMore () {
				return this.count.length >= 20
			},
			listDisabled () {
				return this.loading || this.noMore
			}
		},
		mounted() {
			// this.search(this.searchName || '')
			// this.selectValue = this.value
			document.onkeyup = e => {
				if(this.inputFocus && e.keyCode == 13){
					this.listVisible = true;
					if(!this.sIndex){
						this.search(this.selectValue)
					}
					// this.setCurrent(this.sIndex)
				}
				if(this.listFocus){
					switch (e.keyCode){
						case 40:
							this.sIndex < this.list.length && (this.sIndex += 1)
							this.setCurrent(this.sIndex)
							break;
						case 38:
							this.sIndex > 1 && (this.sIndex -= 1)
							this.setCurrent(this.sIndex)
							break;
						case 13:
							if(this.sIndex){
								if(this.list.length && this.list[this.sIndex - 1]){
									this.listVisible = false
								}
							}
							break;
					}
				}
				

				// setCurrent(list[2])
			}
			document.addEventListener('click', e => {
				if(this.listVisible){
					let mainBox = this.$refs.mainBox
					if (mainBox) {
						if (!mainBox.contains(e.target)) {
							this.listVisible = false
						}
					}
				}
			}, false)
			// document.click = e => {
				
			// }
		},
		methods: {
			setScroll(){
				let tableDom = document.getElementById('scrollTable').getElementsByClassName('el-table__body-wrapper')[0]
				let rowDom = document.getElementById('scrollTable').getElementsByClassName('current-row')[0]
				let hideHeight = this.tableHeight - 38 - rowDom.offsetHeight
				if(rowDom.offsetTop - tableDom.scrollTop > hideHeight){
					tableDom.scrollTop += rowDom.offsetHeight
				}else if(tableDom.scrollTop > rowDom.offsetTop){
					tableDom.scrollTop -= rowDom.offsetHeight
				}
			},
			load(){
				this.loading = true
				setTimeout(() => {
					this.count.push({name: 11111})
					this.loading = false
				}, 2000)
			},
			handleCurrentChange(val){
				this.currentRow = val
			},
			setCurrent(index) {
				this.sIndex = index
		        this.$refs.singleTable.setCurrentRow(this.list[index - 1])
		        this.$nextTick(() => {
		        	this.setScroll()
		        })
		    },
		    rowClick(row){
		    	this.sIndex = -1
		    	this.listVisible = false
		    },
			eval(string){
				return eval(string)
			},
			inputChange(value){
				this.listVisible = true;
				// this.setCurrent(0);
				this.search(value)
			},
			async search(query){
				this.loading = true
				if(this.config.postKey){
					this.config.data[this.config.postKey] = query
				}
				let api = []
				if(!Array.isArray(this.config.api)){
					api.push(this.config.api)
				}else{
					api = this.config.api
				}
				let ress = []
				for(let i=0; i<api.length; i++){
					let res = await request({
					    url: api[i].replace('@', query),
					    method: this.config.method || 'get',
					    data: this.config.data || {},
					    params: this.config.data || {}
					})
					if(res.code == '200' && res.data){
						if(res.data.curr){
							if(res.data.data){
								ress.push(res.data.data)
							}
						}else{
							ress.push(res.data)
						}
					}
				}
				let result = []
				ress.forEach(item => {
					result = result.concat(item)
				})
				this.list = result
				this.list = [{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},{name: 1},]
				this.loading = false
			},
		},
		watch: {
			value: function(val){
				let name = this.searchName || this.changeValue || ''
				if(!val){
					name = ''
				}
				this.search(name)
				// this.selectValue = val
			},
			listVisible: function(val){
				if(val){
					setTimeout(() => {
						this.listFocus = true
					}, 100)
				}else{
					if(this.sIndex){
						this.selectValue = this.currentRow[this.config.label]
						this.changeValue = this.currentRow[this.config.label]
						this.$emit('input', this.currentRow[this.config.value])
						this.$emit('change', this.currentRow)
						this.currentRow = {}
						this.$refs.singleTable.setCurrentRow({})
					}
					this.listFocus = false
					this.sIndex = 0
					this.list = []
				}
			}
		}
	};
</script>
<style scoped>
	.row td{padding-right: 20px;}
	.row td:last-child{padding-right: 0;}
	.row td span{margin-right: 5px;}

	.infinite-list-wrapper{width: 400px;}
</style>

<!-- 

	{
		api: '/sinohis/pension/fee/itemmanager/searchAllItemInfos',
		method: 'post',
		postKey: 'mnemonicCodeOrName',
		label: 'name',
		value: 'mark',
		data: { nurseItemBol: true },
		keys: [
			{ name: '名称', key: 'name' },
			{ name: '价格', key: 'fee' },
			{ name: '价格1', switch: [
				{ name: '价格小于30', key: 'fee', value: 30, color: '#333', symbol: '<' },
	     		{ name: '价格大于30', key: 'fee', value: 30, color: '#ff0000', symbol: '>' },
			]}
		]
	}

 -->